<template>
    <div class="purchase-request-container">
        <!-- 采购申请单标题 -->
        <div class="purchase-header">
            <h2 class="purchase-title">
                <el-icon>
                    <Document />
                </el-icon>
                采购申请单
                <!-- 显示关联的库存不足信息 -->
                <span v-if="shortageInfo.materialName" class="shortage-related">
                    (物料缺库: {{ shortageInfo.materialName }})
                </span>
            </h2>
            <div class="purchase-status">
                <el-tag type="warning" size="large">待提交</el-tag>
            </div>
        </div>

        <!-- 采购申请单表单内容 -->
        <el-card class="purchase-card" shadow="hover">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px" class="purchase-form">

                <!-- 第一行：采购订单编号 + 采购名称 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="采购订单编号" prop="purchaseOrderCode">
                            <el-input v-model="ruleForm.purchaseOrderCode" placeholder="系统自动生成" disabled
                                :prefix-icon="Document" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="采购名称" prop="productMaterialsName">
                            <el-input v-model="ruleForm.productMaterialsName" placeholder="请输入采购物料名称"
                                :prefix-icon="Box" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第二行：采购数量 + 期望到货时间 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="采购数量" prop="purchaseOrderCount">
                            <div class="quantity-control">
                                <el-button class="quantity-btn" @click="decreasePurchaseCount">-</el-button>
                                <el-input-number v-model="ruleForm.purchaseOrderCount" :min="1" :step="1000"
                                    :step-strictly="false" controls-position="right" class="quantity-input"
                                    placeholder="请输入采购数量">
                                </el-input-number>
                                <el-button class="quantity-btn" @click="increasePurchaseCount">+</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="期望到货时间" prop="overTime">
                            <el-date-picker v-model="ruleForm.overTime" type="datetime" placeholder="请选择期望到货时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第三行：供应商选择 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="供应商" prop="vendorId">
                            <el-select v-model="ruleForm.vendorId" placeholder="请选择供应商" style="width: 100%"
                                :prefix-icon="User">
                                <el-option v-for="vendor in vendorList" :key="vendor.id" :label="vendor.vendorName"
                                    :value="vendor.id">
                                    <span style="float: left">{{ vendor.vendorName }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">
                                        {{ vendor.vendorCode }}
                                    </span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 预留位置，可以添加其他字段 -->
                    </el-col>
                </el-row>

                <!-- 第四行：采购描述 -->
                <el-row class="form-row">
                    <el-col :span="24">
                        <el-form-item label="采购描述" prop="purchaseOrderDesc">
                            <el-input v-model="ruleForm.purchaseOrderDesc" type="textarea" :rows="4"
                                placeholder="请输入采购描述" show-word-limit maxlength="200" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 按钮区域 -->
                <el-row class="form-actions">
                    <el-col :span="24">
                        <el-form-item>
                            <div class="button-group">
                                <el-button type="primary" size="large" :icon="Check" @click="submitForm(ruleFormRef)">
                                    提交采购申请
                                </el-button>
                                <el-button size="large" :icon="Refresh" @click="resetForm(ruleFormRef)">
                                    重置表单
                                </el-button>
                                <el-button size="large" :icon="Back" @click="goBack">
                                    返回
                                </el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 采购申请记录 -->
        <el-card class="purchase-history-card" shadow="hover" style="margin-top: 20px">
            <template #header>
                <div class="card-header">
                    <span>采购申请记录</span>
                    <el-button type="primary" @click="refreshPurchaseList">刷新</el-button>
                </div>
            </template>

            <!-- 审批对话框 -->
            <el-dialog v-model="approvalDialogVisible" title="采购申请审批" width="500px" append-to-body destroy-on-close>
                <el-form :model="approvalForm" :rules="approvalRules" ref="approvalFormRef" label-width="100px">
                    <el-form-item label="采购编号">
                        <el-input v-model="approvalForm.purchaseOrderCode" disabled />
                    </el-form-item>
                    <el-form-item label="采购物料">
                        <el-input v-model="approvalForm.productMaterialsName" disabled />
                    </el-form-item>
                    <el-form-item label="审批结果" prop="isApproved">
                        <el-radio-group v-model="approvalForm.isApproved">
                            <el-radio :label="true">通过</el-radio>
                            <el-radio :label="false">驳回</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="审批意见" prop="approvalComment">
                        <el-input v-model="approvalForm.approvalComment" type="textarea" :rows="4"
                            placeholder="请输入审批意见" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="approvalDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitApproval(approvalFormRef)">提交</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 流程设计对话框 -->
            <el-dialog v-model="processDesignVisible" title="审批流程设计" width="1100px" append-to-body destroy-on-close
                class="process-design-dialog">
                <template #header>
                    <div class="process-dialog-header">
                        <div class="process-dialog-title">
                            <i class="el-icon-setting"></i>
                            审批流程设计
                            <span class="process-order-code" v-if="currentProcessOrder">
                                {{ currentProcessOrder.purchaseOrderCode }}
                            </span>
                        </div>
                    </div>
                </template>
                <div class="process-design-container">
                    <!-- 左侧流程节点工具箱 -->
                    <div class="process-tools">
                        <div class="tool-title">流程节点</div>
                        <div class="node-types">
                            <div class="node-type-item" draggable="true" @dragstart="dragStart('start', $event)">
                                <div class="node-circle start-node">开始</div>
                                <div class="node-type-name">开始节点</div>
                            </div>
                            <div class="node-type-item" draggable="true" @dragstart="dragStart('approval', $event)">
                                <div class="node-square approval-node">审批</div>
                                <div class="node-type-name">普通节点</div>
                            </div>
                            <div class="node-type-item" draggable="true" @dragstart="dragStart('condition', $event)">
                                <div class="node-diamond condition-node">条件</div>
                                <div class="node-type-name">条件节点</div>
                            </div>
                            <div class="node-type-item" draggable="true" @dragstart="dragStart('end', $event)">
                                <div class="node-circle end-node">结束</div>
                                <div class="node-type-name">结束节点</div>
                            </div>
                        </div>
                    </div>

                    <!-- 中间流程设计区域 -->
                    <div class="process-design-area">
                        <div class="design-canvas" @dragover="allowDrop($event)" @drop="handleDrop($event)"
                            @click.self="deselectAll">
                            <!-- SVG层用于绘制连接线 -->
                            <svg class="connections-layer" ref="svgContainer">
                                <defs>
                                    <!-- 箭头标记定义 -->
                                    <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5"
                                        orient="auto">
                                        <polygon points="0 0, 10 3.5, 0 7" fill="#8c8c8c" />
                                    </marker>
                                    <marker id="arrowhead-selected" markerWidth="10" markerHeight="7" refX="9"
                                        refY="3.5" orient="auto">
                                        <polygon points="0 0, 10 3.5, 0 7" fill="#409EFF" />
                                    </marker>
                                </defs>
                                <g>
                                    <g v-for="(line, i) in connectionLines" :key="'line-' + i">
                                        <path :d="line.path"
                                            :class="{ 'connection-line': true, 'selected-line': line.selected }"
                                            :marker-end="line.selected ? 'url(#arrowhead-selected)' : 'url(#arrowhead)'"
                                            @click.stop="selectLine(line)" />

                                        <!-- 删除线的按钮 -->
                                        <g v-if="line.selected" class="line-delete-btn" @click.stop="deleteLine(line)">
                                            <circle cx="0" cy="0" r="8" fill="#F56C6C"></circle>
                                            <text x="0" y="0" fill="white" font-size="10" text-anchor="middle"
                                                dy="3">×</text>
                                        </g>
                                    </g>
                                </g>
                            </svg>

                            <!-- 流程节点 -->
                            <div v-for="(node, index) in processNodes" :key="index" class="process-node"
                                :class="{ 'selected-node': node === selectedNode }"
                                :style="{ left: node.x + 'px', top: node.y + 'px' }" @click.stop="selectNode(node)"
                                @mousedown="startDrag($event, node)" draggable="false" :data-node-id="node.id">
                                <!-- 不同类型节点使用不同样式 -->
                                <div v-if="node.type === 'start'" class="node-circle start-node">
                                    <div class="node-content">{{ node.displayName || node.name }}</div>
                                </div>
                                <div v-else-if="node.type === 'end'" class="node-circle end-node">
                                    <div class="node-content">{{ node.displayName || node.name }}</div>
                                </div>
                                <div v-else-if="node.type === 'condition'" class="node-diamond">
                                    <div class="node-content">{{ node.displayName || node.name }}</div>
                                </div>
                                <div v-else class="node-square approval-node">
                                    <div class="node-content">{{ node.displayName || node.name }}</div>
                                </div>
                                <!-- 连接点 - 上下端 -->
                                <div class="connection-point connection-out"
                                    @mousedown.stop="startConnection($event, node, 'out')">
                                </div>
                                <div class="connection-point connection-in"
                                    @mousedown.stop="startConnection($event, node, 'in')">
                                </div>

                                <!-- 删除按钮 -->
                                <div class="node-delete-btn" @click.stop="deleteNode(node)">
                                    <i class="el-icon-delete"></i>
                                </div>
                            </div>

                            <div v-if="processNodes.length === 0" class="empty-canvas">
                                请从左侧添加流程节点
                            </div>

                            <!-- 绘制中的连接线 -->
                            <svg v-if="drawingConnection" class="temp-connection-layer">
                                <path :d="tempConnectionPath" class="temp-connection-line" />
                            </svg>
                        </div>
                    </div>

                    <!-- 右侧节点属性编辑区 -->
                    <div class="node-properties-panel">
                        <div v-if="selectedNode" class="node-properties">
                            <h3>编辑节点</h3>
                            <el-form label-width="100px">
                                <el-form-item label="节点ID：" class="readonly-item">
                                    <el-input v-model="selectedNode.id" disabled />
                                </el-form-item>

                                <el-form-item label="节点名称：">
                                    <el-input v-model="selectedNode.name" />
                                </el-form-item>

                                <template v-if="selectedNode.type === 'approval'">
                                    <el-divider content-position="left">节点管理者设置</el-divider>

                                    <el-form-item label="角色名称：">
                                        <el-select v-model="selectedNode.roleId" placeholder="选择角色" style="width: 100%">
                                            <el-option v-for="role in roleList" :key="role.id" :label="role.roleName"
                                                :value="role.id">
                                                <span class="role-option">{{ role.roleName }}</span>
                                            </el-option>
                                        </el-select>
                                    </el-form-item>

                                    <el-form-item label="部门名称：">
                                        <el-select v-model="selectedNode.deptId" placeholder="选择部门" style="width: 100%"
                                            @change="onDepartmentChange">
                                            <el-option v-for="dept in deptList" :key="dept.id" :label="dept.deptName"
                                                :value="dept.id">
                                                <span class="dept-option">{{ dept.deptName }}</span>
                                            </el-option>
                                        </el-select>
                                    </el-form-item>

                                    <el-form-item label="用户名称：">
                                        <el-select v-model="selectedNode.userId" placeholder="选择用户" style="width: 100%">
                                            <el-option v-for="user in filteredUsers" :key="user.id"
                                                :label="user.realName" :value="user.id">
                                                <span class="user-option">{{ user.realName }}</span>
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>

                                <el-form-item v-if="selectedNode.type === 'condition'">
                                    <el-alert title="条件节点提示" type="info" description="条件节点用于流程分支控制，可以连接多个后续节点"
                                        :closable="false" show-icon>
                                    </el-alert>
                                </el-form-item>

                                <el-form-item>
                                    <el-button type="primary" @click="saveNodeSettings">保存</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                        <div v-else class="no-node-selected">
                            <el-empty description="请选择一个节点进行编辑"></el-empty>
                        </div>
                    </div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="processDesignVisible = false">取消</el-button>
                        <el-button type="primary" @click="saveProcessDesign">保存流程</el-button>
                    </span>
                </template>
            </el-dialog>

            <el-table :data="purchaseList" border style="width: 100%">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="purchaseOrderCode" label="采购编号" width="150" />
                <el-table-column prop="productMaterialsName" label="采购物料名称" width="180" />
                <el-table-column prop="purchaseOrderCount" label="采购数量" width="120" />
                <el-table-column prop="overTime" label="期望到货时间" width="180">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.overTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="purchaseOrderDesc" label="采购描述" min-width="200" />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)">
                            {{ getStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createrPeople" label="创建人" width="120" />
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="vendorName" label="供应商" width="100" />
                <el-table-column fixed="right" label="操作" width="280">
                    <template #default="scope">
                        <el-button type="primary" link @click="handleSubmitOutAsk(scope.row)"
                            v-if="scope.row.status === 2"
                            :disabled="isOutAskSubmitted(scope.row.purchaseOrderCode)"
                            :title="isOutAskSubmitted(scope.row.purchaseOrderCode) ? '已提交入库单' : '提交入库单'">
                            {{ isOutAskSubmitted(scope.row.purchaseOrderCode) ? '已提交' : '提交入库单' }}
                        </el-button>
                        <el-button type="primary" @click="openApprovalDialog(scope.row)"
                            v-if="scope.row.status != 2">审批</el-button>
                        <el-button type="success" @click="createNode(scope.row)"
                            v-if="scope.row.status != 2 &&scope.row.status != 1 &&scope.row.status != 3" >设计审批流程</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
    <el-dialog v-model="dialogVisible" title="流转设置" width="1300">
        <el-button type="success" @click="addrows()">新增一行</el-button>
        <el-table :data="cfgtableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="180" />
            <el-table-column prop="nodeName" label="节点名称" width="180" >
                <template #default="scope">
                    <el-input v-model="scope.row.nodeName" placeholder="请输入节点名称" />
                </template>
            </el-table-column>
            <el-table-column prop="prevNodeId" label="上一个节点" width="180" >
                <template #default="scope">
                    <el-select v-model="scope.row.prevNodeId" placeholder="请选择" clearable style="width: 100%">
                        <el-option label="请选择" value="0"></el-option>
                        <el-option label="人事审批" value="1"></el-option>
                        <el-option label="财务审批" value="2"></el-option>
                        <el-option label="董事长审批" value="3"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="nextNodeId" label="下一个节点" width="180" >
                <template #default="scope">
                    <el-select v-model="scope.row.nextNodeId" placeholder="请选择" clearable style="width: 100%">
                        <el-option label="请选择" value="0"></el-option>
                        <el-option label="人事审批" value="1"></el-option>
                        <el-option label="财务审批" value="2"></el-option>
                        <el-option label="董事长审批" value="3"></el-option>
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="nodeDescription" label="节点描述" width="180" >
                <template #default="scope">
                    <el-input v-model="scope.row.nodeDescription" placeholder="请输入节点描述" />
                </template>
            </el-table-column>
            <el-table-column prop="timeLimit" label="审批时限（小时）" width="210" >
                <template #default="scope">
                    <el-input v-model="scope.row.timeLimit" placeholder="请输入审批时限（小时）" />
                </template>
            </el-table-column>
            <el-table-column  label="操作" width="180" >
      <template v-slot="score">
        <el-button type="danger" @click="delRows(score.$index)">删除</el-button>
      </template>
    </el-table-column>
        </el-table>
        <template #footer>
      <div class="dialog-footer">
        <el-button @click="saveCfgData()">保存</el-button>
        <el-button type="primary" @click="dialogVisible = false">
          取消
        </el-button>
      </div>
    </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import { useRoute, useRouter } from 'vue-router'
import { Document, Box, Check, Refresh, Back, User } from '@element-plus/icons-vue'
import { clear } from 'echarts/types/src/util/throttle.js';
onMounted(() => {
    getcfgtableData()
})
const pinia = useCounterStore();
const route = useRoute();
const router = useRouter();

//#region 设计审批流程
const dialogVisible=ref(false)
const idser=ref(0)
//打开流程设置
const createNode=(idr:any)=>{
    idser.value=idr.id
    //反填流转设置
    
  dialogVisible.value=true
}
const cfgtableData=ref(<any>[{
      "processId": idser.value,
      "nodeName": "",
      "nodeType": 1,
      "prevnodeId": null,
      "nextnodeId": null,
      "nodeDescription": "",
      "timeLimit": null,
}])
const page=ref({
    processId: idser.value
    
})
const getcfgtableData=()=>{
    axios.get("/api/ApprocalProcess/GetConfigurationNode",{params:page}).then(res=>{
        cfgtableData.value=res.data.data;
    })
}
//清空审批数据源
const clearCfgData=()=>{
    cfgtableData.value=[{
        "processId": idser.value,
        "nodeName": "",
        "nodeType": 1,
        "prevNodeId": null,
        "nextNodeId": null,
        "nodeDescription": "",
        "timeLimit": null,
    }];
}
const saveCfgData=()=>{
    debugger
    axios.post("/api/ApprocalProcess/ConfigurationNode",{processId:idser.value,createFromFieIdDtos:cfgtableData.value}).then(res=>{
        if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            dialogVisible.value=false
            getPurchaseRequestList()

        }else{
            ElMessage.error(res.data.message)
        }
    })
}
//新增一行
const addrows=()=>{
    cfgtableData.value.push({
      "processId": idser.value,
      "nodeName": "",
      "nodeType": 1,
      "prevnodeId": null,
      "nextnodeId": null,
      "nodeDescription": "",
      "timeLimit": null,
    })
}
//删除一行
const delRows=(index:any)=>{
  cfgtableData.value.splice(index,1)
}

//#endregion





// 审批对话框相关
const approvalDialogVisible = ref(false);
const approvalFormRef = ref<FormInstance>();
const currentPurchaseOrder = ref<any>(null);

// 审批表单数据
const approvalForm = reactive({
    purchaseOrderId: 0,
    purchaseOrderCode: '',
    productMaterialsName: '',
    isApproved: true,
    approvalComment: '',
    currentUserId: 0,
    currentUserRole: ''
});

// 流程设计相关
const processDesignVisible = ref(false);
const selectedNode = ref<any>(null);
const currentProcessOrder = ref<any>(null);
const processNodes = ref<any[]>([]);
const svgContainer = ref<HTMLElement | null>(null);

// 拖拽相关
const isDragging = ref(false);
const draggedNode = ref<any>(null);
const dragStartX = ref(0);
const dragStartY = ref(0);
const dragOffsetX = ref(0);
const dragOffsetY = ref(0);

// 连接线相关
const connectionLines = ref<any[]>([]);
const selectedLine = ref<any>(null);
const drawingConnection = ref(false);
const connectionSource = ref<any>(null);
const connectionType = ref<string>('');
const tempConnectionPath = ref('');

// 用户过滤
const filteredUsers = ref<any[]>([]);

// 角色列表
const roleList = ref<any[]>([
    { id: 1, roleName: '管理员' },
    { id: 2, roleName: '财务' },
    { id: 3, roleName: '采购' },
    { id: 4, roleName: '董事长' }
]);

// 用户列表
const userList = ref<any[]>([
    { id: 1, realName: '张三' },
    { id: 2, realName: '李四' },
    { id: 3, realName: '王五' }
]);

// 部门列表
const deptList = ref<any[]>([
    { id: 1, deptName: '人事部' },
    { id: 2, deptName: '财务部' },
    { id: 3, deptName: '采购部' },
    { id: 4, deptName: '技术部' }
]);

// 审批表单验证规则
const approvalRules = reactive<FormRules>({
    isApproved: [
        { required: true, message: '请选择审批结果', trigger: 'change' }
    ],
    approvalComment: [
        { required: true, message: '请输入审批意见', trigger: 'blur' },
        { min: 2, max: 200, message: '审批意见长度应为2-200个字符', trigger: 'blur' }
    ]
});

// 库存不足相关信息
const shortageInfo = reactive({
    materialName: '',
    shortageCount: 0,
    requestCount: 0
});

// 采购申请记录列表
const purchaseList = ref<any[]>([]);

// 供应商列表
const vendorList = ref<any[]>([]);

// 已提交入库单的采购单号列表
const submittedOutAskCodes = ref<string[]>([]);

// 分页信息
const pagination = reactive({
    currentPage: 1,
    pageSize: 5,
    total: 0
});

onMounted(() => {
    // 生成采购编号
    generatePurchaseCode();

    // 设置默认的期望到货时间（7天后）
    const defaultDate = new Date();
    defaultDate.setDate(defaultDate.getDate() + 7);
    ruleForm.overTime = defaultDate.toISOString().substring(0, 19);

    // 获取供应商列表
    getVendorList();

    // 检查是否有从库存不足页面传来的参数
    if (route.query.materialName || route.query.shortageCount || route.query.requestCount) {
        const materialName = route.query.materialName as string;
        const materialId = route.query.materialId as string;
        const shortageCount = Number(route.query.shortageCount) || 0;
        const requestCount = Number(route.query.requestCount) || 0;

        // 设置库存不足信息
        shortageInfo.materialName = materialName || '';
        shortageInfo.shortageCount = shortageCount;
        shortageInfo.requestCount = requestCount;

        // 预填表单
        if (materialName) {
            ruleForm.productMaterialsName = materialName;
            ruleForm.productMaterialsId = materialId ? Number(materialId) : null; // 设置物料ID
            ruleForm.purchaseOrderCount = Math.max(shortageCount, 1000); // 至少1000个
            ruleForm.purchaseOrderDesc = `因库存不足需要采购物料"${materialName}"，缺少数量: ${shortageCount}`;
        }
    }

    // 获取采购申请记录
    getPurchaseRequestList();

    // 获取已提交入库单的采购单号列表
    getSubmittedOutAskCodes();

    // 检查是否需要刷新页面（从入库申请单页面返回）
    if (route.query.refresh === 'true') {
        // 延迟一点时间再刷新，确保页面已完全加载
        setTimeout(() => {
            refreshPurchaseList();
            ElMessage.success('已成功提交入库单，采购单状态已更新');
        }, 500);
    }
})

// 表单引用
const ruleFormRef = ref<FormInstance>()

// 表单数据 - 根据后端接口字段设计
const ruleForm = reactive({
    "purchaseOrderCode": "", // 采购订单编号 - CG + 随机六位数
    "purchaseOrderCount": 0, // 采购数量
    "productMaterialsName": "", // 采购名称（物料名称）
    "productMaterialsId": null as number | null, // 物料ID，从物料库存反填
    "overTime": "", // 超时时间
    "purchaseOrderDesc": "", // 采购描述
    "status": 0, // 状态，默认为0（不显示在页面）
    "createrPeople": pinia.piniaDto?.realName || pinia.piniaDto?.accountName || "admin", // 创建人
    "vendorId": null as number | null // 供应商外键，用户选择
})

// 表单验证规则
const rules = reactive<FormRules>({
    purchaseOrderCode: [
        { required: true, message: '采购订单编号不能为空', trigger: 'blur' },
    ],
    productMaterialsName: [
        { required: true, message: '请输入采购物料名称', trigger: 'blur' },
    ],
    purchaseOrderCount: [
        { required: true, message: '请输入采购数量', trigger: 'change' },
        { type: 'number', min: 1, message: '采购数量必须大于0', trigger: 'change' }
    ],
    overTime: [
        { required: false, message: '请选择期望到货时间', trigger: 'change' },
    ],
    vendorId: [
        { required: true, message: '请选择供应商', trigger: 'change' },
    ],
    purchaseOrderDesc: [
        { required: true, message: '请输入采购描述', trigger: 'blur' },
    ],
})

// 生成采购编号 - CG + 随机六位数
const generatePurchaseCode = () => {
    const randomNumber = Math.floor(100000 + Math.random() * 900000).toString();
    ruleForm.purchaseOrderCode = 'CG' + randomNumber;
}

// 增加采购数量（点击加号添加1000）
const increasePurchaseCount = () => {
    if (!ruleForm.purchaseOrderCount) {
        ruleForm.purchaseOrderCount = 1000;
    } else {
        ruleForm.purchaseOrderCount = Number(ruleForm.purchaseOrderCount) + 1000;
    }
}

// 减少采购数量
const decreasePurchaseCount = () => {
    if (!ruleForm.purchaseOrderCount || Number(ruleForm.purchaseOrderCount) <= 1000) {
        ElMessage.warning('采购数量不能小于1000');
        return;
    }
    ruleForm.purchaseOrderCount = Number(ruleForm.purchaseOrderCount) - 1000;
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 准备提交数据，确保格式正确
            const submitData = {
                purchaseOrderCode: ruleForm.purchaseOrderCode,
                purchaseOrderCount: Number(ruleForm.purchaseOrderCount),
                productMaterialsName: ruleForm.productMaterialsName,
                productMaterialsId: ruleForm.productMaterialsId, // 添加物料ID
                purchaseOrderDesc: ruleForm.purchaseOrderDesc,
                createrPeople: ruleForm.createrPeople,
                vendorId: ruleForm.vendorId ? Number(ruleForm.vendorId) : null,
                status: Number(ruleForm.status),
                // 时间格式处理
                overTime: ruleForm.overTime || null
            };

            console.log('提交数据:', submitData); // 调试日志

            // 调用后端API添加采购申请单
            axios.post('/api/ProductionModules/AddPurchaseOrder', submitData).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success('采购申请单提交成功');
                    // 清空表单
                    clearForm(formEl);
                    // 刷新采购记录列表
                    getPurchaseRequestList();
                } else {
                    ElMessage.error(res.data.message || '提交失败，请重试');
                }
            }).catch(error => {
                ElMessage.error('网络异常，提交失败');
                console.error('Submit error:', error);
                if (error.response && error.response.data) {
                    console.error('Server response:', error.response.data);
                }
            });
        } else {
            console.log('表单验证失败!', fields)
        }
    })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    generatePurchaseCode();
    // 重新设置默认时间
    const defaultDate = new Date();
    defaultDate.setDate(defaultDate.getDate() + 7);
    ruleForm.overTime = defaultDate.toISOString().substring(0, 19);
}

// 清空表单（提交成功后使用）
const clearForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 清空所有字段
    ruleForm.productMaterialsName = '';
    ruleForm.purchaseOrderCount = 0;
    ruleForm.purchaseOrderDesc = '';
    // 重置供应商为第一个（如果有的话）
    if (vendorList.value.length > 0) {
        ruleForm.vendorId = vendorList.value[0].id;
    } else {
        ruleForm.vendorId = null;
    }
    // 重新生成编号
    generatePurchaseCode();
    // 重新设置默认时间
    const defaultDate = new Date();
    defaultDate.setDate(defaultDate.getDate() + 7);
    ruleForm.overTime = defaultDate.toISOString().substring(0, 19);
    // 清空库存不足信息
    shortageInfo.materialName = '';
    shortageInfo.shortageCount = 0;
    shortageInfo.requestCount = 0;
}

// 重置部分表单（保留关键信息）
const resetPartialForm = () => {
    ruleForm.purchaseOrderCount = 0;
    // 重新设置默认时间
    const defaultDate = new Date();
    defaultDate.setDate(defaultDate.getDate() + 7);
    ruleForm.overTime = defaultDate.toISOString().substring(0, 19);
}

// 返回上一页
const goBack = () => {
    router.push('/InventoryShow')
}

// 获取供应商列表
const getVendorList = async () => {
    try {
        const response = await axios.get('/api/ProductionModules/GetVendor');

        if (response.data.code === 200) {
            vendorList.value = response.data.totalPage || [];
            // 如果有供应商数据且表单中vendorId为空，设置默认选择第一个供应商
            if (vendorList.value.length > 0 && !ruleForm.vendorId) {
                ruleForm.vendorId = vendorList.value[0].id;
            }
        } else {
            console.error('获取供应商列表失败:', response.data.message);
            ElMessage.error('获取供应商列表失败');
        }
    } catch (error) {
        console.error('获取供应商列表异常:', error);
        ElMessage.error('获取供应商列表异常');
    }
}

// 获取采购申请记录列表
const getPurchaseRequestList = async () => {
    try {
        const params = {
            PageIndex: pagination.currentPage,
            PageSize: pagination.pageSize,
            ProductMaterialsName: '' // 根据图片中的API参数
        };

        const response = await axios.get('/api/ProductionModules/GetPurchaseOrder', { params });

        if (response.data.code === 200) {
            // 添加调试日志，查看API返回的数据
            console.log('采购单列表API返回数据:', response.data);

            purchaseList.value = response.data.totalPage || [];
            pagination.total = response.data.totalcount || 0;

            // 检查第一条记录是否包含productMaterialsId字段
            if (purchaseList.value.length > 0) {
                console.log('第一条采购记录:', purchaseList.value[0]);

                // 输出所有字段名称，查看是否有类似的字段
                console.log('第一条采购记录的所有字段:', Object.keys(purchaseList.value[0]));

                // 检查是否有productMaterialsId字段或类似字段
                const firstRecord = purchaseList.value[0];
                console.log('productMaterialsId:', firstRecord.productMaterialsId);
                console.log('productMaterialId:', firstRecord.productMaterialId); // 检查可能的拼写变体
                console.log('materialId:', firstRecord.materialId); // 检查可能的替代字段
            }
        } else {
            console.error('获取采购申请记录失败:', response.data.message);
        }
    } catch (error) {
        console.error('获取采购申请记录异常:', error);
    }
}

// 刷新采购申请记录
const refreshPurchaseList = () => {
    getPurchaseRequestList();
    // 同时刷新已提交入库单的采购单号列表
    getSubmittedOutAskCodes();
    ElMessage.success('数据已刷新');
}

/**
 * 获取已提交入库单的采购单号列表
 */
const getSubmittedOutAskCodes = async () => {
    try {
        // 调用API获取所有入库申请单
        const response = await axios.get('/api/ProductionModules/GetMaterialOutAsk', {
            params: {
                PageIndex: 1,
                PageSize: 1000, // 获取足够多的记录以确保包含所有数据
                ProductMaterialsName: ''
            }
        });

        if (response.data.code === 200) {
            // 提取所有入库申请单的采购单号
            const outAskData = response.data.totalPage || [];
            // 更新已提交入库单的采购单号列表
            submittedOutAskCodes.value = outAskData.map((item: any) => item.purchaseOrderCode);
            console.log('已提交入库单的采购单号:', submittedOutAskCodes.value);
        } else {
            console.error('获取入库申请单列表失败:', response.data.message);
        }
    } catch (error) {
        console.error('获取入库申请单列表异常:', error);
    }
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
    pagination.pageSize = size;
    getPurchaseRequestList();
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
    pagination.currentPage = page;
    getPurchaseRequestList();
}

// 打开审批对话框
const openApprovalDialog = (row: any) => {
    currentPurchaseOrder.value = row;
    approvalForm.purchaseOrderId = row.id;
    approvalForm.purchaseOrderCode = row.purchaseOrderCode;
    approvalForm.productMaterialsName = row.productMaterialsName;
    approvalForm.isApproved = true;
    approvalForm.approvalComment = '';
    // 使用管理员ID作为默认值
    approvalForm.currentUserId = 1;
    approvalForm.currentUserRole = pinia.piniaDto?.roleName || '管理员';

    approvalDialogVisible.value = true;
}

// 提交审批
const submitApproval = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;

    await formEl.validate((valid, fields) => {
        if (valid) {
            // 构建请求数据
            const approvalData = {
                purchaseOrderId: approvalForm.purchaseOrderId,
                isApproved: approvalForm.isApproved,
                approvalComment: approvalForm.approvalComment,
                currentUserId: approvalForm.currentUserId,
                currentUserRole: approvalForm.currentUserRole
            };

            console.log('提交审批数据:', approvalData);

            // 调用审批API
            axios.post('/api/ApprocalProcess/ApprovalPurchaseOrders', approvalData)
                .then(res => {
                    if (res.data && res.data.data === true) {
                        ElMessage.success('审批提交成功');
                        approvalDialogVisible.value = false;

                        // 更新本地状态
                        if (currentPurchaseOrder.value) {
                            currentPurchaseOrder.value.status = approvalForm.isApproved ? 1 : 3;
                        }

                        // 刷新列表
                        refreshPurchaseList();
                    } else {
                        ElMessage.error(res.data?.message || '审批提交失败');
                    }
                })
                .catch(error => {
                    console.error('审批提交错误:', error);
                    ElMessage.error('审批提交出错，请稍后重试');
                });
        } else {
            console.log('表单验证失败:', fields);
        }
    });
}

// 打开流程设计对话框
const openProcessDesign = (row: any) => {
    currentProcessOrder.value = row;
    processDesignVisible.value = true;

    // 清空现有连接线
    connectionLines.value = [];

    // 初始化流程节点，创建默认的开始和结束节点
    const defaultStartNode = {
        id: generateUUID(),
        type: 'start',
        name: '开始',
        x: 100,
        y: 100
    };

    const defaultEndNode = {
        id: generateUUID(),
        type: 'end',
        name: '结束',
        x: 100,
        y: 300
    };

    processNodes.value = [defaultStartNode, defaultEndNode];

    // 显示加载提示
    const loadingMessage = ElMessage({
        message: '正在加载流程节点...',
        type: 'info',
        duration: 0
    });

    // 查询已有流程节点
    getProcessNodes(row.id);

    // 3秒后关闭加载提示，避免一直显示
    setTimeout(() => {
        loadingMessage.close();
    }, 3000);
}

// 生成UUID
const generateUUID = (): string => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0,
            v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// 获取已有流程节点
const getProcessNodes = (purchaseOrderId: number) => {
    // 尝试使用businessId作为参数名，并转为小写路径
    axios.get(`/api/ApprovalFlow/getProcessNodes`, {
        params: {
            businessId: purchaseOrderId
        }
    })
        .then(res => {
            console.log('获取流程节点响应:', res);
            if (res.data && res.data.code === 200 && res.data.data) {
                // 如果已有流程节点数据，覆盖默认节点
                if (res.data.data.length > 0) {
                    console.log('成功获取流程节点:', res.data.data);
                    processNodes.value = res.data.data;
                } else {
                    console.log('未找到现有流程节点，使用默认节点');
                }
            } else {
                console.warn('获取流程节点返回异常:', res.data);
            }
        })
        .catch(error => {
            console.error('获取流程节点失败:', error);
            console.log('尝试使用另一种API路径获取...');

            // 备选路径1: 尝试使用另一种命名格式
            axios.get(`/api/ApprovalFlow/nodes/${purchaseOrderId}`)
                .then(res => {
                    if (res.data && res.data.code === 200 && res.data.data) {
                        processNodes.value = res.data.data;
                        console.log('通过备选路径1获取成功');
                    }
                })
                .catch(err => {
                    console.error('备选路径1失败:', err);

                    // 备选路径2: 尝试原路径但使用不同参数名
                    axios.get(`/api/ApprovalFlow/GetProcessNodes`, {
                        params: {
                            businessId: purchaseOrderId
                        }
                    })
                        .then(res => {
                            if (res.data && res.data.code === 200 && res.data.data) {
                                processNodes.value = res.data.data;
                                console.log('通过备选路径2获取成功');
                            }
                        })
                        .catch(e => {
                            console.error('备选路径2也失败:', e);
                            ElMessage.warning('无法获取现有流程节点，将使用默认流程节点');
                        });
                });
        });
}

// 拖动节点相关方法
const dragStart = (type: string, event: DragEvent) => {
    if (event.dataTransfer) {
        event.dataTransfer.setData('nodeType', type);
        event.dataTransfer.effectAllowed = 'copy';
    }
}

const allowDrop = (event: DragEvent) => {
    event.preventDefault();
}

const handleDrop = (event: DragEvent) => {
    event.preventDefault();
    if (!event.dataTransfer) return;

    const type = event.dataTransfer.getData('nodeType');
    if (!type) return;

    const canvasRect = (event.currentTarget as HTMLElement).getBoundingClientRect();
    const x = event.clientX - canvasRect.left;
    const y = event.clientY - canvasRect.top;

    addNodeAt(type, x, y);
}

// 添加节点到特定位置
const addNodeAt = (type: string, x: number, y: number) => {
    const newNode = {
        id: generateUUID(),
        type,
        name: getDefaultNodeName(type),
        x: x,
        y: y,
        roleId: type === 'approval' ? roleList.value[0]?.id : null,
        userId: type === 'approval' ? null : null,
        deptId: type === 'approval' ? null : null,
        connections: {
            in: [],
            out: []
        }
    };

    processNodes.value.push(newNode);
    selectNode(newNode);
}

// 添加流程节点
const addNode = (type: string) => {
    addNodeAt(type, 200, 200 + processNodes.value.length * 100);
}

// 开始拖动节点
const startDrag = (event: MouseEvent, node: any) => {
    // 忽略右键点击
    if (event.button !== 0) return;

    isDragging.value = true;
    draggedNode.value = node;
    const canvasRect = (event.currentTarget as HTMLElement).parentElement?.getBoundingClientRect();

    if (canvasRect) {
        dragStartX.value = event.clientX;
        dragStartY.value = event.clientY;
        dragOffsetX.value = node.x;
        dragOffsetY.value = node.y;

        // 添加全局鼠标事件
        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
    }
}

// 鼠标移动处理
const onMouseMove = (event: MouseEvent) => {
    if (!isDragging.value || !draggedNode.value) return;

    const dx = event.clientX - dragStartX.value;
    const dy = event.clientY - dragStartY.value;

    // 计算新位置（相对于画布）
    draggedNode.value.x = dragOffsetX.value + dx;
    draggedNode.value.y = dragOffsetY.value + dy;

    // 更新连接线
    updateConnectionLines();
}

// 鼠标抬起处理
const onMouseUp = () => {
    isDragging.value = false;
    draggedNode.value = null;

    // 移除全局事件
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
}

// 连接线相关方法
const startConnection = (event: MouseEvent, node: any, type: string) => {
    event.stopPropagation();
    drawingConnection.value = true;
    connectionSource.value = node;
    connectionType.value = type;

    // 设置初始连接线路径
    const sourcePoint = getConnectionPoint(node, type);
    tempConnectionPath.value = `M ${sourcePoint.x} ${sourcePoint.y}`;

    // 添加鼠标移动和抬起事件
    document.addEventListener('mousemove', onConnectionMove);
    document.addEventListener('mouseup', onConnectionEnd);
}

// 计算连接点位置
const getConnectionPoint = (node: any, type: string): { x: number, y: number } => {
    const nodeWidth = 100; // 假设节点宽度为100px
    const nodeHeight = 60; // 假设节点高度为60px

    if (type === 'out') {
        // 底部连接点
        return {
            x: node.x + nodeWidth / 2,
            y: node.y + nodeHeight
        };
    } else {
        // 顶部连接点
        return {
            x: node.x + nodeWidth / 2,
            y: node.y
        };
    }
}

// 绘制连接线移动
const onConnectionMove = (event: MouseEvent) => {
    if (!drawingConnection.value || !connectionSource.value) return;

    const canvasElement = document.querySelector('.design-canvas');
    if (!canvasElement) return;

    const canvasRect = canvasElement.getBoundingClientRect();
    const x = event.clientX - canvasRect.left;
    const y = event.clientY - canvasRect.top;

    const sourcePoint = getConnectionPoint(connectionSource.value, connectionType.value);

    // 更新临时连接线
    tempConnectionPath.value = `M ${sourcePoint.x} ${sourcePoint.y} L ${x} ${y}`;
}

// 结束连接线绘制
const onConnectionEnd = (event: MouseEvent) => {
    if (!drawingConnection.value || !connectionSource.value) return;

    // 查找目标节点
    const target = findTargetNodeForConnection(event);
    console.log('连接终点:', target);

    try {
        // 如果找到有效的目标节点，创建连接
        if (target && target.node !== connectionSource.value) {
            // 检查连接类型是否匹配（out -> in）
            if (connectionType.value === 'out' && target.type === 'in') {
                console.log('建立连接: source -> target');
                createConnection(connectionSource.value, target.node);
                ElMessage.success('连接创建成功');
            } else if (connectionType.value === 'in' && target.type === 'out') {
                console.log('建立连接: target -> source');
                createConnection(target.node, connectionSource.value);
                ElMessage.success('连接创建成功');
            } else {
                console.warn('连接类型不匹配:', { sourceType: connectionType.value, targetType: target.type });
                ElMessage.warning('连接端点类型不匹配，请使用输出点连接到输入点');
            }
        } else if (target && target.node === connectionSource.value) {
            ElMessage.warning('不能连接到自身');
        } else {
            console.log('没有找到有效的连接目标');
        }
    } catch (error) {
        console.error('创建连接时出错:', error);
        ElMessage.error('创建连接失败，请重试');
    } finally {
        // 重置连接状态
        drawingConnection.value = false;
        connectionSource.value = null;
        connectionType.value = '';
        tempConnectionPath.value = '';

        // 移除事件监听
        document.removeEventListener('mousemove', onConnectionMove);
        document.removeEventListener('mouseup', onConnectionEnd);
    }
}

// 查找目标连接节点
const findTargetNodeForConnection = (event: MouseEvent): { node: any, type: string } | null => {
    // 获取所有连接点
    const connectionPoints = document.querySelectorAll('.connection-point');

    for (const point of connectionPoints) {
        const rect = point.getBoundingClientRect();

        // 检查鼠标是否在连接点上
        if (
            event.clientX >= rect.left && event.clientX <= rect.right &&
            event.clientY >= rect.top && event.clientY <= rect.bottom
        ) {
            // 获取节点和连接类型
            const nodeElement = point.closest('.process-node') as HTMLElement;
            if (!nodeElement) continue;

            const nodeId = nodeElement.getAttribute('data-node-id');
            if (!nodeId) {
                console.error('节点缺少data-node-id属性');
                continue;
            }

            const node = processNodes.value.find(n => n.id === nodeId);
            if (!node) {
                console.error('找不到节点:', nodeId);
                continue;
            }

            const type = point.classList.contains('connection-in') ? 'in' : 'out';
            console.log('找到连接目标:', { nodeId, type });
            return { node, type };
        }
    }

    return null;
}

// 创建连接线
const createConnection = (sourceNode: any, targetNode: any) => {
    console.log('创建连接:', { source: sourceNode.id, target: targetNode.id });

    // 确保节点有connections属性
    if (!sourceNode.connections) sourceNode.connections = { in: [], out: [] };
    if (!targetNode.connections) targetNode.connections = { in: [], out: [] };

    // 避免重复连接
    const existingConnection = connectionLines.value.find(line =>
        (line.source.id === sourceNode.id && line.target.id === targetNode.id)
    );

    if (existingConnection) {
        console.log('已存在相同连接，不重复创建');
        return;
    }

    // 创建新连接
    const connection = {
        id: generateUUID(),
        source: sourceNode,
        target: targetNode,
        selected: false,
        path: getConnectionPath(sourceNode, targetNode)
    };

    // 添加到连接线数组
    connectionLines.value.push(connection);
    console.log('连接创建成功:', connection);

    // 更新节点的连接信息
    if (!sourceNode.connections.out.includes(targetNode.id)) {
        sourceNode.connections.out.push(targetNode.id);
    }
    if (!targetNode.connections.in.includes(sourceNode.id)) {
        targetNode.connections.in.push(sourceNode.id);
    }

    // 更新连接线路径
    updateConnectionLines();
}

// 计算连接线路径
const getConnectionPath = (sourceNode: any, targetNode: any): string => {
    const sourcePoint = getConnectionPoint(sourceNode, 'out');
    const targetPoint = getConnectionPoint(targetNode, 'in');

    // 使用贝塞尔曲线平滑连接 - 为垂直方向优化
    const dy = Math.abs(targetPoint.y - sourcePoint.y) / 2;

    // 计算线条删除按钮位置 (中间点)
    if (selectedLine.value && selectedLine.value.source === sourceNode && selectedLine.value.target === targetNode) {
        const midX = (sourcePoint.x + targetPoint.x) / 2;
        const midY = (sourcePoint.y + targetPoint.y) / 2;

        // 更新删除按钮位置
        const deleteBtn = document.querySelector('.line-delete-btn');
        if (deleteBtn) {
            const transform = `translate(${midX}, ${midY})`;
            deleteBtn.setAttribute('transform', transform);
        }
    }

    return `M ${sourcePoint.x} ${sourcePoint.y} C ${sourcePoint.x} ${sourcePoint.y + dy}, ${targetPoint.x} ${targetPoint.y - dy}, ${targetPoint.x} ${targetPoint.y}`;
}

// 更新所有连接线
const updateConnectionLines = () => {
    for (const line of connectionLines.value) {
        line.path = getConnectionPath(line.source, line.target);
    }
}

// 选择连接线
const selectLine = (line: any) => {
    // 取消所有选择
    deselectAll();

    // 选择当前线
    line.selected = true;
    selectedLine.value = line;
}

// 删除节点
const deleteNode = (node: any) => {
    if (!node) return;

    // 确认删除提示
    ElMessageBox.confirm(`确定要删除节点 "${node.name}" 吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 删除与该节点相关的所有连接线
        connectionLines.value = connectionLines.value.filter(line => {
            return line.source.id !== node.id && line.target.id !== node.id;
        });

        // 从节点列表中移除该节点
        const index = processNodes.value.findIndex(n => n.id === node.id);
        if (index !== -1) {
            processNodes.value.splice(index, 1);
        }

        // 如果当前选中的是这个节点，取消选中
        if (selectedNode.value && selectedNode.value.id === node.id) {
            selectedNode.value = null;
        }

        ElMessage.success('节点删除成功');
    }).catch(() => {
        // 用户取消删除
    });
}

// 删除连接线
const deleteLine = (line: any) => {
    if (!line) return;

    // 确认删除提示
    ElMessageBox.confirm('确定要删除此连接线吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 从源节点的输出连接中移除
        if (line.source.connections && line.source.connections.out) {
            const outIndex = line.source.connections.out.indexOf(line.target.id);
            if (outIndex !== -1) {
                line.source.connections.out.splice(outIndex, 1);
            }
        }

        // 从目标节点的输入连接中移除
        if (line.target.connections && line.target.connections.in) {
            const inIndex = line.target.connections.in.indexOf(line.source.id);
            if (inIndex !== -1) {
                line.target.connections.in.splice(inIndex, 1);
            }
        }

        // 从连接线数组中移除
        const index = connectionLines.value.findIndex(l => l.id === line.id);
        if (index !== -1) {
            connectionLines.value.splice(index, 1);
        }

        // 如果当前选中的是这条线，取消选中
        if (selectedLine.value && selectedLine.value.id === line.id) {
            selectedLine.value = null;
        }

        ElMessage.success('连接线删除成功');
    }).catch(() => {
        // 用户取消删除
    });
}

// 取消所有选择
const deselectAll = () => {
    selectedNode.value = null;

    // 取消所有线的选择
    for (const line of connectionLines.value) {
        line.selected = false;
    }

    selectedLine.value = null;
}

// 获取默认节点名称
const getDefaultNodeName = (type: string): string => {
    switch (type) {
        case 'start':
            return '开始';
        case 'end':
            return '结束';
        case 'approval':
            return '审批节点' + (processNodes.value.filter(n => n.type === 'approval').length + 1);
        case 'condition':
            return '条件节点' + (processNodes.value.filter(n => n.type === 'condition').length + 1);
        default:
            return '新节点';
    }
}

// 选择节点
const selectNode = (node: any) => {
    // 先取消所有选择
    deselectAll();

    // 再选择当前节点
    selectedNode.value = node;

    // 如果是审批节点，根据部门ID过滤用户
    if (node.type === 'approval' && node.deptId) {
        filterUsersByDepartment(node.deptId);
    } else {
        // 默认加载所有用户
        filteredUsers.value = [...userList.value];
    }
}

// 根据部门ID过滤用户
const filterUsersByDepartment = (deptId: number) => {
    // 实际情况下应当从API获取特定部门的用户
    // 这里我们用模拟数据演示
    if (!deptId) {
        filteredUsers.value = [...userList.value];
        return;
    }

    // 假设用户有departmentId字段
    filteredUsers.value = userList.value.filter(user => {
        // 模拟数据没有部门关联，这里随机分配部门方便测试
        const userDeptId = user.id % deptList.value.length + 1;
        return userDeptId === deptId;
    });
}

// 部门变更事件
const onDepartmentChange = (deptId: number) => {
    if (selectedNode.value) {
        // 部门变更后清空已选用户
        selectedNode.value.userId = null;
        // 过滤该部门下的用户
        filterUsersByDepartment(deptId);
    }
}

// 保存节点设置
const saveNodeSettings = () => {
    if (!selectedNode.value) return;

    // 更新节点显示名称 (针对审批节点可显示关联人员)
    if (selectedNode.value.type === 'approval') {
        // 如果选择了用户，显示用户名
        if (selectedNode.value.userId) {
            const selectedUser = userList.value.find(u => u.id === selectedNode.value.userId);
            if (selectedUser) {
                // 保留原始名称，并附加处理人
                selectedNode.value.displayName = `${selectedNode.value.name} (${selectedUser.realName})`;
            }
        }
    }

    ElMessage.success('节点设置已保存');
}

// 获取节点样式类
const getNodeClass = (type: string): string => {
    switch (type) {
        case 'start':
            return 'node-circle start-node';
        case 'end':
            return 'node-circle end-node';
        case 'approval':
            return 'node-square approval-node';
        case 'condition':
            return 'node-diamond condition-node';
        default:
            return '';
    }
}

// 保存流程设计
const saveProcessDesign = () => {
    if (!currentProcessOrder.value) {
        ElMessage.error('没有选择采购单');
        return;
    }

    if (processNodes.value.length < 2) {
        ElMessage.warning('至少需要包含开始和结束节点');
        return;
    }

    // 检查是否有开始和结束节点
    const hasStart = processNodes.value.some(node => node.type === 'start');
    const hasEnd = processNodes.value.some(node => node.type === 'end');

    if (!hasStart || !hasEnd) {
        ElMessage.warning('流程必须包含开始和结束节点');
        return;
    }

    // 构建连接关系数据
    const connectionsData = connectionLines.value.map(line => ({
        sourceId: line.source.id,
        targetId: line.target.id,
        lineId: line.id
    }));

    // 完全按照API文档规范构造请求体
    const saveData = {
        // 基础信息
        processId: 0, // 新建流程时为0
        processName: "采购审批流程-" + currentProcessOrder.value.purchaseOrderCode,
        businessId: currentProcessOrder.value.id,
        businessCode: currentProcessOrder.value.purchaseOrderCode,
        businessName: currentProcessOrder.value.productMaterialsName,
        businessType: "PurchaseOrder",
        // 用户信息
        currentUserId: 1,
        currentUserName: pinia.piniaDto?.realName || "管理员",
        // 节点数据 - API中是nodes小写
        nodes: processNodes.value.map(node => {
            // 根据节点的roleId查找对应的角色名称
            const role = roleList.value.find(r => r.id === node.roleId);
            const roleName = role ? role.roleName : "默认角色";

            // 根据节点的userId查找对应的用户名称
            const user = userList.value.find(u => u.id === node.userId);
            const userName = user ? user.realName : "默认用户";

            // 根据节点的deptId查找对应的部门名称
            const dept = deptList.value.find(d => d.id === node.deptId);
            const deptName = dept ? dept.deptName : "默认部门";

            // 确保所有字段名称与API完全匹配
            const nodeData = {
                id: node.id,
                nodeType: node.type,
                nodeName: node.name || "节点",
                nodeDescription: `${node.name || "节点"}描述`,
                // 位置信息
                x: node.x,
                y: node.y,
                // 审批人角色信息
                approverRoleId: node.roleId || 0,
                approverRoleName: roleName,
                // 审批人用户信息
                approverUserId: node.userId || 0,
                approverUserName: userName,
                // 部门信息
                departmentId: node.deptId || 0,
                departmentName: deptName,
                // 添加可能缺少的其他必需字段
                width: 100, // 节点宽度
                height: node.type === 'start' || node.type === 'end' ? 60 : 40, // 节点高度
                status: 0, // 节点状态
                sort: 0 // 节点顺序
            };

            // 根据节点类型添加特定属性
            if (node.type === 'approval') {
                // 使用另一种方式添加字段，避免TS类型错误
                Object.assign(nodeData, { approvalType: 0 }); // 审批类型
            }

            return nodeData;
        }),
        // 使用API文档中的连接线格式
        connections: connectionLines.value.map((line, index) => ({
            id: line.id,
            lineId: line.id, // 可能API需要lineId字段
            sourceNodeId: line.source.id,
            targetNodeId: line.target.id,
            label: "", // 连接线标签
            condition: "", // 连接线条件
            sort: index // 连接线排序
        }))
    };

    console.log('保存流程设计数据:', saveData);

    // 打印完整的请求数据，方便调试
    console.log('完整的保存流程设计数据:', JSON.stringify(saveData, null, 2));

    // 显示保存中的消息提示
    ElMessage({
        message: '正在保存流程设计...',
        type: 'info',
        duration: 0
    });

    // 调用保存API - 使用API文档中指定的正确地址
    axios.post('/api/ApprovalFlow/saveDesign', saveData)
        .then(res => {
            // 清除之前的消息
            ElMessage.closeAll();
            console.log('保存流程设计响应:', res);

            if (res.data && res.data.code === 200) {
                ElMessage.success({
                    message: '流程设计保存成功',
                    duration: 3000
                });
                processDesignVisible.value = false;

                // 刷新采购单列表，更新流程状态
                refreshPurchaseList();
            } else {
                // 显示详细错误信息
                const errorMsg = res.data?.message || '保存返回异常';
                const errorDetails = res.data?.errors ? JSON.stringify(res.data.errors) : '';
                console.error('保存失败详情:', errorMsg, errorDetails);

                ElMessageBox.alert(
                    `错误详情: ${errorMsg} ${errorDetails}`,
                    '保存流程设计失败',
                    {
                        confirmButtonText: '确定',
                        type: 'warning'
                    }
                );
            }
        })
        .catch(error => {
            // 清除之前的消息
            ElMessage.closeAll();

            // 详细记录错误信息
            console.error('保存流程设计失败:', error);
            console.error('错误详情:', error.response?.data || error.message);
            console.log('完整请求体:', JSON.stringify(saveData, null, 2));

            // 显示更详细的错误信息
            const errorMsg = error.response?.data?.message || error.message || '未知错误';
            const errorDetails = error.response?.data?.errors ?
                JSON.stringify(error.response.data.errors) :
                (error.response?.status ? `HTTP状态码: ${error.response.status}` : '');

            // 使用对话框展示详细错误信息
            ElMessageBox.alert(
                `错误信息: ${errorMsg}<br>详细信息: ${errorDetails}<br><br>请检查网络连接或联系系统管理员。`,
                '保存流程设计失败',
                {
                    confirmButtonText: '确定',
                    dangerouslyUseHTMLString: true,
                    type: 'error'
                }
            );
        });
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
    if (!dateString) return '';
    return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
}

// 获取状态标签类型
const getStatusType = (status: number) => {
    switch (status) {
        case 0:
            return 'warning'; // 待审核
        case 1:
            return 'primary'; // 进行中
        case 2:
            return 'success'; // 已完成
        case 3:
            return 'danger'; // 已取消
        default:
            return 'info';
    }
}

// 获取状态文本
const getStatusText = (status: number) => {
    switch (status) {
        case 0:
            return '待审核';
        case 1:
            return '进行中';
        case 2:
            return '已完成';
        case 3:
            return '已取消';
        default:
            return '未知';
    }
}

/**
 * 判断采购单是否已提交入库单
 * @param purchaseOrderCode 采购单号
 * @returns 是否已提交入库单
 */
const isOutAskSubmitted = (purchaseOrderCode: string): boolean => {
    return submittedOutAskCodes.value.includes(purchaseOrderCode);
}

/**
 * 处理提交入库单按钮点击事件
 * @param row 当前行数据
 */
const handleSubmitOutAsk = (row: any) => {
    // 检查采购单状态是否为"已完成"
    if (row.status !== 2) {
        ElMessage.warning('只有状态为"已完成"的采购单才能提交入库申请');
        return;
    }
    
    // 如果已经提交过入库单，则不允许再次提交
    if (isOutAskSubmitted(row.purchaseOrderCode)) {
        ElMessage.warning('该采购单已提交入库单，不能重复提交');
        return;
    }

    // 添加调试日志，查看当前行数据
    console.log('当前采购单行数据:', row);

    // 检查是否有productMaterialsId，如果没有，尝试从其他字段获取或设置默认值
    let materialId = row.productMaterialsId;

    // 输出所有可能的字段名称
    console.log('采购单行的所有字段:', Object.keys(row));

    // 如果productMaterialsId不存在，尝试查找其他可能的字段
    if (materialId === undefined || materialId === null) {
        // 尝试不同的可能字段名称
        const possibleFields = ['productMaterialId', 'materialId', 'productMaterialsID', 'productMaterialID', 'id'];

        for (const field of possibleFields) {
            if (row[field] !== undefined && row[field] !== null) {
                console.log(`找到替代字段 ${field}:`, row[field]);
                materialId = row[field];
                break;
            }
        }

        // 如果仍然没有找到，尝试使用id字段
        if ((materialId === undefined || materialId === null) && row.id) {
            console.log('采用id字段作为备选:', row.id);
            materialId = row.id;
        }
    }

    // 如果仍然没有有效的ID，设置为0作为默认值
    if (materialId === undefined || materialId === null) {
        console.log('无法获取有效的物料ID，设置默认值0');
        materialId = 0;
    }

    console.log('最终使用的物料ID:', materialId);

    // 跳转到物料入库申请单页面，并传递采购单相关参数
    router.push({
        path: '/MaterialOutAsk',
        query: {
            purchaseOrderCode: row.purchaseOrderCode, // 采购单号
            productMaterialsName: row.productMaterialsName, // 入库物料名称
            productMaterialsId: materialId.toString(), // 物料ID（转为字符串，因为query参数都是字符串）
            outAskCount: row.purchaseOrderCount, // 入库数量（默认与采购数量相同）
            vendorName: row.vendorName // 供应商名称
        }
    });
}
</script>

<style scoped>
/* 主容器样式 */
.purchase-request-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 40px);
}

/* 采购标题区域 */
.purchase-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 24px;
    background: linear-gradient(135deg, #ff9a56 0%, #ff6b6b 100%);
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(255, 154, 86, 0.3);
}

.purchase-title {
    display: flex;
    align-items: center;
    color: white;
    font-size: 24px;
    font-weight: 600;
    margin: 0;
}

.purchase-title .el-icon {
    margin-right: 12px;
    font-size: 28px;
}

.shortage-related {
    font-size: 16px;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.9);
    margin-left: 12px;
    background: rgba(255, 255, 255, 0.1);
    padding: 4px 12px;
    border-radius: 6px;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.purchase-status {
    display: flex;
    align-items: center;
}

/* 采购卡片样式 */
.purchase-card,
.purchase-history-card {
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid #e4e7ed;
    background: white;
}

.purchase-card:hover,
.purchase-history-card:hover {
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
    transition: all 0.3s ease;
}

/* 表单样式 */
.purchase-form {
    padding: 24px;
}

.form-row {
    margin-bottom: 24px;
}

.form-row:last-of-type {
    margin-bottom: 0;
}

/* 数量控制样式 */
.quantity-control {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
}

.quantity-btn {
    flex: 0 0 auto;
    padding: 8px 12px;
    font-size: 16px;
    font-weight: bold;
}

.quantity-input {
    flex: 1;
}

/* 表单项样式优化 */
:deep(.el-form-item__label) {
    color: #303133;
    font-weight: 600;
    font-size: 14px;
    line-height: 1.6;
}

:deep(.el-input) {
    border-radius: 8px;
}

:deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #dcdfe6;
    transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
    border-color: #c0c4cc;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

:deep(.el-textarea__inner) {
    border-radius: 8px;
    border: 1px solid #dcdfe6;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    resize: vertical;
}

:deep(.el-date-editor) {
    width: 100%;
}

/* 按钮区域样式 */
.form-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 2px solid #f0f2f5;
}

.button-group {
    display: flex;
    justify-content: center;
    gap: 16px;
}

.button-group .el-button {
    min-width: 120px;
    height: 44px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.button-group .el-button--primary {
    background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
    border: none;
}

.button-group .el-button--primary:hover {
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.button-group .el-button:not(.el-button--primary) {
    background: white;
    border: 1px solid #d9d9d9;
    color: #666;
}

.button-group .el-button:not(.el-button--primary):hover {
    border-color: #409eff;
    color: #409eff;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

/* 历史记录卡片头部 */
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    font-size: 16px;
    color: #303133;
}

/* 分页容器样式 */
.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px;
    background-color: #f9fafb;
    border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .purchase-request-container {
        padding: 16px;
    }

    .purchase-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
        padding: 16px;
    }

    .purchase-title {
        font-size: 20px;
    }

    .purchase-form {
        padding: 16px;
    }

    .form-row .el-col {
        margin-bottom: 16px;
    }

    .button-group {
        flex-direction: column;
        align-items: center;
    }

    .button-group .el-button {
        width: 100%;
        max-width: 200px;
    }

    .quantity-control {
        flex-direction: column;
        gap: 8px;
    }

    .quantity-btn,
    .quantity-input {
        width: 100%;
    }
}

/* 动画效果 */
.purchase-card,
.purchase-history-card {
    animation: slideInUp 0.6s ease-out;
}

@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.purchase-header {
    animation: slideInDown 0.6s ease-out;
}

@keyframes slideInDown {
    from {
        opacity: 0;
        transform: translateY(-30px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 流程设计样式 */
.process-design-dialog :deep(.el-dialog__body) {
    padding: 0;
}

.process-dialog-header {
    padding: 15px 20px;
    background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
    color: white;
    border-radius: 6px 6px 0 0;
}

.process-dialog-title {
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 10px;
}

.process-order-code {
    font-size: 14px;
    opacity: 0.8;
    margin-left: 10px;
    font-weight: normal;
}

.process-design-container {
    display: flex;
    height: 650px;
    border: 1px solid #e4e7ed;
    border-radius: 0 0 6px 6px;
    background-color: #f9fafc;
    overflow: hidden;
}

.process-tools {
    width: 200px;
    border-right: 1px solid #e4e7ed;
    padding: 20px;
    background-color: #f0f2f5;
    box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
    overflow-y: auto;
}

.tool-title {
    font-weight: bold;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px dashed #dcdfe6;
    color: #303133;
    text-align: center;
    font-size: 16px;
}

.node-types {
    display: flex;
    flex-direction: column;
    gap: 25px;
    padding: 10px;
}

.node-type-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: grab;
    transition: all 0.2s ease;
    padding: 10px;
    border-radius: 8px;
    background-color: rgba(255, 255, 255, 0.6);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    border: 1px dashed transparent;
}

.node-type-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    background-color: white;
    border-color: #dcdfe6;
}

.node-type-item:active {
    cursor: grabbing;
}

.node-type-name {
    margin-top: 10px;
    font-size: 14px;
    color: #606266;
    font-weight: 500;
}

.node-circle {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-weight: bold;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
    border: 2px solid transparent;
    position: relative;
    overflow: hidden;
}

.node-circle::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0) 50%);
    pointer-events: none;
}

.start-node {
    background: linear-gradient(120deg, #67C23A 0%, #85CE61 100%);
}

.end-node {
    background: linear-gradient(120deg, #F56C6C 0%, #F78989 100%);
}

.node-square {
    width: 100px;
    height: 60px;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-weight: bold;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
    border: 2px solid transparent;
    position: relative;
    overflow: hidden;
}

.node-square::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0) 50%);
    pointer-events: none;
}

.approval-node {
    background: linear-gradient(120deg, #409EFF 0%, #79BBFF 100%);
}

.node-diamond {
    width: 70px;
    height: 70px;
    transform: rotate(45deg);
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-weight: bold;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
    border: 2px solid transparent;
    background: linear-gradient(120deg, #E6A23C 0%, #F0C78A 100%);
    position: relative;
    overflow: hidden;
}

.node-diamond::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0) 50%);
    pointer-events: none;
}

.node-type-item .node-diamond span,
.process-node .node-diamond .node-content {
    transform: rotate(-45deg);
}

.process-design-area {
    flex: 2;
    display: flex;
    flex-direction: column;
}

.design-canvas {
    flex: 1;
    padding: 20px;
    background-color: #ffffff;
    background-image: url('');
    position: relative;
    overflow: auto;
    min-height: 600px;
    height: 100%;
    box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
}

.empty-canvas {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #909399;
    font-size: 16px;
    padding: 30px 50px;
    background-color: rgba(255, 255, 255, 0.7);
    border: 2px dashed #dcdfe6;
    border-radius: 8px;
    backdrop-filter: blur(2px);
}

.process-node {
    position: absolute;
    cursor: move;
    transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    z-index: 2;
    user-select: none;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    min-width: 100px;
    filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1));
}

.process-node .node-content {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 500;
}

.process-node:hover {
    filter: drop-shadow(0 6px 12px rgba(0, 0, 0, 0.2));
    transform: translateY(-2px);
}

.process-node.selected-node {
    filter: drop-shadow(0 8px 16px rgba(0, 0, 0, 0.15));
    transform: translateY(-3px);
}

.process-node.selected-node .node-circle,
.process-node.selected-node .node-square,
.process-node.selected-node .node-diamond {
    border-color: #409EFF;
    border-width: 3px;
}

/* 连接线样式 */
.connections-layer,
.temp-connection-layer {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;
}

.connections-layer path {
    pointer-events: auto;
    transition: all 0.3s ease;
}

.connection-line {
    stroke: #8c8c8c;
    stroke-width: 2.5px;
    fill: none;
    pointer-events: stroke;
    stroke-linecap: round;
    filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.1));
    /* 确保线段本身连接到起点和终点 */
    stroke-dasharray: 0;
    stroke-dashoffset: 0;
}

.selected-line {
    stroke: #409EFF;
    stroke-width: 3px;
    filter: drop-shadow(0 1px 5px rgba(64, 158, 255, 0.5));
}

.temp-connection-line {
    stroke: #409EFF;
    stroke-width: 2px;
    stroke-dasharray: 5, 5;
    fill: none;
    animation: dash 1s linear infinite;
}

@keyframes dash {
    to {
        stroke-dashoffset: -10;
    }
}

/* 连接点样式 */
.connection-point {
    position: absolute;
    width: 14px;
    height: 14px;
    background-color: #ffffff;
    border: 2px solid #409EFF;
    border-radius: 50%;
    z-index: 3;
    cursor: crosshair;
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.7);
    opacity: 0.5;
    /* 总是保持一定的可见度 */
    transition: all 0.2s ease;
}

.process-node:hover .connection-point {
    opacity: 1;
    transform: scale(1.2) translateX(-50%);
}

.connection-in {
    left: 50%;
    top: -6px;
    transform: translateX(-50%);
}

.connection-in::after {
    content: '';
    position: absolute;
    top: 4px;
    left: 50%;
    transform: translateX(-50%);
    border-top: 6px solid transparent;
    border-bottom: 0;
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    border-bottom: 6px solid #409EFF;
}

.connection-out {
    left: 50%;
    bottom: -6px;
    transform: translateX(-50%);
}

.connection-out::after {
    content: '';
    position: absolute;
    bottom: 4px;
    left: 50%;
    transform: translateX(-50%);
    border-bottom: 6px solid transparent;
    border-top: 0;
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    border-top: 6px solid #409EFF;
}

/* 删除按钮样式 */
.node-delete-btn {
    position: absolute;
    top: -8px;
    right: -8px;
    width: 18px;
    height: 18px;
    background-color: #F56C6C;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 12px;
    cursor: pointer;
    opacity: 0;
    transition: all 0.2s ease;
    z-index: 4;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.process-node:hover .node-delete-btn {
    opacity: 1;
}

.node-delete-btn:hover {
    transform: scale(1.2);
    background-color: #ff4949;
}

.connection-point:hover {
    transform: scale(1.5) translateX(-50%) !important;
    box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.9);
    opacity: 1;
    background-color: #f0f9ff;
}

.node-properties {
    padding: 20px;
    background-color: white;
    height: 100%;
    overflow-y: auto;
    box-shadow: -4px 0 12px rgba(0, 0, 0, 0.05);
    border-left: 1px solid #e4e7ed;
}

.node-properties-panel {
    width: 280px;
    background-color: #f9fafc;
    border-left: 1px solid #e4e7ed;
    overflow-y: auto;
}

.no-node-selected {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    padding: 20px;
}

.node-properties h3 {
    font-size: 18px;
    margin-top: 0;
    margin-bottom: 20px;
    color: #303133;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    font-weight: 600;
    text-align: center;
}

.readonly-item :deep(.el-input__inner) {
    color: #606266;
    background-color: #f5f7fa;
    cursor: default;
}

.role-option,
.dept-option,
.user-option {
    display: flex;
    align-items: center;
    height: 100%;
    font-size: 14px;
}

.process-design-dialog :deep(.el-divider__text) {
    background-color: #f0f2f5;
    color: #606266;
    font-weight: 600;
}

.process-design-dialog :deep(.el-alert--info) {
    background-color: #f4f4f5;
    border: 1px solid #e9e9eb;
    border-radius: 8px;
}

.process-design-dialog :deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
}

.process-design-dialog :deep(.el-dialog__footer) {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #f9fafc;
}

.process-design-dialog :deep(.el-button) {
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.process-design-dialog :deep(.el-button--primary) {
    background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
    border: none;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.process-design-dialog :deep(.el-button--primary:hover) {
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(64, 158, 255, 0.5);
}
</style>
